#!/bin/sh
# ============================================================================
#
# This script collects the white,trapped,grey values from a patched
# greyscanner script and stores them into a RRD database.
#
#   olli hauer

# directory where we store all the RRD databases
RRDDIR=/var/db/rrd

# the RRD database
RRDDB=obspamd.rrd

# the rrdtool
RRDTOOL=%%PREFIX%%/bin/rrdtool

# additional RRD values log
LOG=/var/log/spamd_rrd.log
USE_RRD=0

# ============================================================================
# we get the values as $1 in the form
#  white:trapped:grey
#
# values for connects will be calculated from this script
# 
# $SCAN_INTERVAL = 600; # from greyscanner
#
# calculate RRD 
#  graph 1: (update every $SCAN_INTERVAL)
#   values / hour => 3600 / 600 = 6
#   values / day  => 6 * 24     = 144
#   values / 10d  => 7 * 6 * 24 = 1440
#
#  graph 2: (consolidate every 30min from graph 1 for 40 days => every 3. value from hour)
#   values / day  => 24 * 2     = 48
#   values / 40days => 48 * 40  = 1920
#
# ============================================================================
# interval   Nr. Values      duration
# 10m        1440            7d    (  7d         * 24h * 6   values per hour)  = 1008
# 30m        1920            31d   (  (31+7)d    * 24h * 2   values per hour)  = 1824
# 1h          960            31d   (  (31+31+7)d * 24h * 1   values per hour)  = 1656
# 2h          240            60d   (  (60+31+7)d * 24h * 0.5 values per hour)  = 1176
# 1d                         400d  (  (400+60+31+7)d * 24h * 

create_rrddb(){
[ ! -d ${RRDDIR} ] && mkdir ${RRDDIR}

${RRDTOOL} create ${RRDDIR}/${RRDDB} 	\
	--start N 			\
	DS:white:GAUGE:1200:0:U 	\
	DS:trapped:GAUGE:1200:0:U 	\
	DS:grey:GAUGE:1200:0:U 		\
	DS:connects:GAUGE:1200:0:U	\
	RRA:AVERAGE:0.5:1:1008		\
	RRA:AVERAGE:0.5:3:1824		\
	RRA:AVERAGE:0.5:6:1656		\
	RRA:AVERAGE:0.5:12:1176		\
	RRA:AVERAGE:0.5:144:498		\
	RRA:MIN:0.5:1:1008		\
	RRA:MIN:0.5:3:1824		\
	RRA:MIN:0.5:6:1656		\
	RRA:MIN:0.5:12:1176		\
	RRA:MIN:0.5:144:498		\
	RRA:MAX:0.5:1:1008		\
	RRA:MAX:0.5:3:1824		\
	RRA:MAX:0.5:6:1656		\
	RRA:MAX:0.5:12:1176		\
	RRA:MAX:0.5:144:498
}


if [ -x ${RRDTOOL} ]; then
    USE_RRD=1
    [ ! -f ${RRDDIR}/${RRDDB} ] && create_rrddb
fi

test ${1} 
if [ $? -eq 0 ]; then
	connects=`/usr/bin/sockstat -c4 -p 8025 | /usr/bin/wc -l | /usr/bin/awk '{print $1}'`
	if [ ${connects} -gt 1 ]; then
		connects=$(( ${connects} -1 ))
	else
		connects=0
	fi

#	printf "%s:%s\n" `date -j "+%s"` ${1}:${connects} >> ${LOG}
    [ ${USE_RRD} -eq 1 ] && ${RRDTOOL} update ${RRDDIR}/${RRDDB} N:${1}:${connects}
else
	exit 1
fi

